// pages/search/search.js
import goodsApi from '../../service/goodsApi';
const app = getApp()
const SUCCESS_CODE = app.globalData.codeConfig.errCode.SUCCESS_CODE

Page({
    /**
     * 页面的初始数据
     */
    data: {
        talentInfo: {},
        talentId: '',
        // showKeyWord: true,
        searchKey: '',
        searchKeyRecommend: '',
        loading: false,
        defaultShow: false,
        historySearchList: [], // 搜索历史
        keywordList: [], // 热门搜索
        snapUpFlag: false, // 是否需要抢货
        goodsList: [],
        startPage: 1,
	    pageSize: 50,
        loadTips: '上拉加载',
        upAbled: false, // 是否能上拉加载

        showBuyPopup: false, // 是否展示购买弹窗
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        let that = this
        // 获取搜索历史
        that.setData({
            historySearchList: wx.getStorageSync('historySearchList'),
            talentInfo: wx.getStorageSync('talentInfo'),
            talentId: wx.getStorageSync('talentId'),
            searchKeyRecommend: app.globalData.searchKeyRecommend
        })
        that.hotSearch()
    },

    // 获取热门搜索关键词
    hotSearch() {
        goodsApi.hotSearch().then( (res) => {
            if (res.data.errCode === SUCCESS_CODE) {
                this.setData({
                    keywordList: [...res.data.data.keywordList]
                })
            } else {
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                })
            }
        })
    },
    
    // 搜索框值变化
    onChange(e) {
        this.setData({
            searchKey: e.detail.value.trim()
        })
        if (this.data.searchKey == '') {
            this.setData({
                defaultShow: false
            })
        }
    },
    // 搜索框搜索
    onConfirm() {
        this.setData({
            startPage: 1,
            loadTips: '加载中...'
        })
        this.onSearch()
    },
    // 搜索
    onSearch(e) {
        let that = this
        let _searchKey = that.data.searchKey
        // 直接搜索placeholder中的内容，将搜索历史加进去
        if (that.data.searchKey === '') {
            that.setData({
                searchKey: that.data.searchKeyRecommend
            })
            _searchKey = that.data.searchKeyRecommend
        }

        // 本地存储搜索历史关键词，并最多10条
        let _historySearchList = [...new Set([_searchKey, ...that.data.historySearchList])]
        _historySearchList = _historySearchList.length > 10 ? _historySearchList.slice(0, 10) : _historySearchList
        wx.setStorage({
            key: "historySearchList",
            data: _historySearchList
        })
        
        that.setData({
            historySearchList: _historySearchList
        })
        
        if (that.data.startPage === 1) {
            that.setData({
                loading: true,
                defaultShow: false,
                goodsList: []
            })
        }

        // 取前50个字符
        let _content = that.data.searchKey.length > 50 ? that.data.searchKey.substr(0, 50) : that.data.searchKey
        let params = {
            startPage: that.data.startPage,
            pageSize: that.data.pageSize,
            content: _content
        }
        console.log(params);
        goodsApi.searchGoods(params).then( res => {
            if (res.data.errCode === SUCCESS_CODE) {
                let _goodsList = that.data.goodsList.concat(res.data.data.goodsList)
                that.setData({
                    loading: false,
                    snapUpFlag: res.data.data.snapUpFlag,
                    goodsList: _goodsList
                })
                if (that.data.goodsList.length === 0) {
                    that.setData({
                        defaultShow: true,
                    })
                } else {
                    that.setData({
                        defaultShow: false
                    })
                }
                if (res.data.data.goodsList.length < that.data.pageSize) {
                    that.setData({
                        loadTips: '暂无更多数据',
                        upAbled: false
                    })
                } else {
                    that.setData({
                        upAbled: true,
                        loadTips: '上拉加载'
                    })
                }
            } else {
                that.setData({
                    loading: false
                })
                wx.showToast({
                    title: res.data.msg,
                    icon: 'none'
                })
            }
        })
    },
    // 清除搜索框内容
    onClear() {
        this.setData({
            searchKey: '',
            defaultShow: false
        })
    },

    // 点击立即购买
    onRushBuy (e) {
        let that = this
        that.setData({
            showBuyPopup: true,
            goodsInfo: e.currentTarget.dataset.item
        })
        this.selectComponent('#buyPopup').onRushBuy()
    },

    // 搜索取消按钮
    cancelSearch() {
        wx.navigateBack({
            delta: 1
        })
    },

    // 删除搜索历史记录
    delSearchHistory() {
        this.setData({
            historySearchList: []
        })
        wx.removeStorageSync('historySearchList')
    },
    // 点击关键词搜索
    onKeyWordSearch(e) {
        let keyWord = e.currentTarget.dataset.keyword
        this.setData({
            searchKey: keyWord,
            startPage: 1,
            loadTips: '加载中...'
        })
        this.onSearch()
    },

    // 点击商品券进入商品详情页
    toGoodsDetail(e) {
        let goodsId = e.currentTarget.dataset.goodsid
        wx.navigateTo({
            url: `../goodsDetail/goodsDetail?goodsId=${goodsId}`
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        if (this.data.upAbled) {
            this.setData({
                startPage: this.data.startPage + 1,
                loadTips: '加载中...'
            })
            this.onSearch()
        }
    },
        /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function(e) {
        if (e.from === 'button') {
            let data = e.target.dataset
            // 商品分享
            return {
                title: data.name,
                path: data.url,
                imageUrl: data.img
            }
        }
    }
})